package service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import constant.Constant;
import dao.ChapterDao;
import entity.Chapter;
import exception.DataAccessException;
import exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import service.ChapterService;
import vo.ChapterVo;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Service
public class ChapterServiceImpl implements ChapterService {

    @Autowired
    ChapterDao chapterDao;

    // “课程章节管理”页面加载章节信息
    @Override
    public PageInfo<Chapter> loadChapter(ChapterVo chapterVo) throws ServiceException {
        PageHelper.startPage(chapterVo.getPageNo(), Constant.PAGE_SIZE_2);
        List<Chapter> chapters = chapterDao.selectChapterByVo(chapterVo);
        PageInfo<Chapter> info = new PageInfo<>(chapters);
        return info;
    }

    // “课程章节管理”页面添加章节信息
    @Override
    public boolean addChapter(Chapter chapter) throws ServiceException {
//        添加创建日期和默认状态
        chapter.setCreate_date(new Date());
        chapter.setStatus(Constant.STATUS_ENABLE);

        try {
//            章节标题不能重复
            if (null != chapterDao.selectByTitle(chapter.getTitle())) {
                throw new ServiceException("该章节标题已存在！");
            }
//            添加章节信息
            if (1 == chapterDao.insertChapter(chapter)) {
                return true;
            }
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return false;
    }

    // “课程章节管理”页面查询修改章节的信息
    @Override
    public Chapter showToModify(Integer id) throws ServiceException {
        return chapterDao.selectById(id);
    }

    // “课程章节管理”页面修改章节的信息
    @Override
    public boolean modifyChapter(Chapter chapter) throws ServiceException {
        //        添加创建日期
        chapter.setCreate_date(new Date());

        try {
//            章节标题不能重复
            Chapter title = chapterDao.selectByTitle(chapter.getTitle());
            System.out.println("chapter="+chapter);
            System.out.println("title="+title);
            if (null != title && title.getId() != chapter.getId()) {
                throw new ServiceException("该章节标题已存在！");
            }
//            修改章节信息
            if (1 == chapterDao.updateChapterById(chapter)) {
                return true;
            }
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        System.out.println("modifyChapter结束");
        return false;
    }

//    根据课程id查询全部章节
    @Override
    public List<Chapter> loadChapterByCourseId(Integer course_id) throws ServiceException {
        return chapterDao.selectAllByCourseId(course_id);
    }

    @Override
    public List<Chapter> selectChapterByCourseId(int course_id) throws ServiceException {
        return chapterDao.selectChapterByCourseId(course_id);
    }
}
